<template>
  <h1>注册页面</h1>
  <el-input placeholder="请输入用户名" v-model="query.username"></el-input>
  <el-input placeholder="请输入密码" v-model="query.password"></el-input>
  <el-input placeholder="请再次输入密码" v-model="query.re_password"></el-input>
  <el-button type="primary" @click="register">注册</el-button>
  <router-link to="/login">已有账号，去登录</router-link>
</template>

<script setup>
import {onMounted, ref} from 'vue'
import axios from "axios";
import {ElMessage} from "element-plus";
import router from "@/router/index.js";

const query = ref({
  username: null,
  password: null,
  re_password: null
})
const register = () => {
  if (query.value.username === null || query.value.password === null || query.value.re_password === null) {
    ElMessage.error('请输入完整信息')
  }
  if (query.value.password !== query.value.re_password) {
    ElMessage.error('两次密码不一致')
  } else {
    axios.post('http://localhost:8000/app/register/', query.value)
        .then(res => {
          const data = res.data
          console.log(res.data)
          if (data.code === 200 && data.msg === '注册成功') {
            router.push('/login')
            ElMessage.success('注册成功')
          } else {
            if (data.code === 400 && data.msg === '用户名或邮箱或手机号已存在') {
              ElMessage.error('用户名或邮箱或手机号已存在')
            } else {
              if (data.data["non_field_errors"][0] === "密码长度必须在6-16位之间") {
                ElMessage.error(data.data["non_field_errors"][0])
              }

            }
          }

        })

  }
}

</script>

